<template>
  <a-card 
    :title="project.name" 
    :bordered="true"
    class="project-card"
    :hoverable="true"
  >
    <template #extra>
      <div v-if="isAdmin" class="action-buttons">
        <a-button 
          type="link" 
          size="small" 
          @click="onEdit"
          :icon="h(EditOutlined)"
        >
          编辑
        </a-button>
        <a-popconfirm
          title="确定要删除这个项目吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onDelete"
        >
          <a-button 
            type="link" 
            size="small" 
            danger
            :icon="h(DeleteOutlined)"
          >
            删除
          </a-button>
        </a-popconfirm>
      </div>
    </template>

    <div class="project-description">
      {{ project.description || '暂无描述' }}
    </div>

    <div class="environments-section">
      <h4>环境配置</h4>
      <div class="environments-list">
        <div 
          v-for="environment in project.environments" 
          :key="environment.id"
          class="environment-item"
        >
          <div class="environment-info">
            <span class="environment-name">{{ environment.name }}</span>
          </div>
          
          <!-- 手风琴式规则显示 -->
          <div class="environment-rules" v-if="environment.hosts.length > 0">
            <a-collapse 
              size="small"
              class="rules-accordion"
              :bordered="false"
            >
              <a-collapse-panel 
                :key="environment.id"
                class="rules-panel"
              >
                <template #header>
                  <div class="panel-header">
                    <span class="rules-count">{{ environment.hosts.length }} 条规则</span>
                    <a-tag 
                      :color="getEnvironmentTypeColor(environment.type)" 
                      size="small"
                      class="env-type-tag"
                    >
                      {{ getEnvironmentTypeName(environment.type) }}
                    </a-tag>
                  </div>
                </template>
                
                <div class="rules-content">
                  <div 
                    v-for="(host, index) in environment.hosts" 
                    :key="index"
                    class="rule-item"
                  >
                    <a-tag 
                      size="small" 
                      class="host-tag"
                      :class="{ 'clickable-rule': isAdmin }"
                      @click="onEdit"
                      :title="isAdmin ? '点击编辑项目' : '请先登录管理员账号'"
                    >
                      {{ host }}
                    </a-tag>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>

          <div class="environment-control">
            <a-switch
              :checked="environment.isActive"
              :loading="switchLoading[environment.id]"
              @change="(checked: boolean) => onEnvironmentToggle(environment.id, checked, environment.type)"
            />
            <span class="switch-label">
              {{ environment.isActive ? '已激活' : '未激活' }}
            </span>
            
            <!-- 倒计时浮层 -->
            <div 
              v-if="countdownStates[environment.id]?.isCountingDown"
              class="countdown-overlay"
            >
              <div class="countdown-content">
                <div class="countdown-text">
                  {{ countdownStates[environment.id]?.targetState ? '激活' : '取消激活' }}规则正在生效中
                  {{ Math.ceil(countdownStates[environment.id]?.timeLeft || 0) }}秒
                </div>
                <div class="progress-container">
                  <div 
                    class="progress-bar"
                    :style="{ width: (countdownStates[environment.id]?.progress || 0) + '%' }"
                  ></div>
                </div>
                <div class="countdown-actions">
                  <a-button 
                    size="small" 
                    type="text" 
                    @click="clearCountdown(environment.id)"
                  >
                    取消
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { ref, h, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import type { ProjectCardProps, EnvironmentType } from '@/types';
import { projectApi } from '@/api';
import { storageManager } from '@/utils/storage';

// Props
const props = defineProps<ProjectCardProps>();

// Emits
const emit = defineEmits<{
  edit: [projectId: string];
  delete: [projectId: string];
  refresh: [];
  environmentChange: [envId: string, checked: boolean, envType: EnvironmentType];
}>();

const activeEnvironments = ref<string[]>([]);
// 响应式数据
const switchLoading = ref<Record<string, boolean>>({});

// 倒计时相关状态
const countdownStates = ref<{
  [key: string]: {
  isCountingDown: boolean;
  timeLeft: number;
  targetState: boolean; // true=激活, false=取消激活
  timer?: number;
  progress: number; // 0-100 进度百分比
  }
}>({});

// 监听父组件传递的环境变化，实时更新开关状态
const updateActiveEnvironments = () => {
  activeEnvironments.value = storageManager.getActiveEnvironments();
  
  // 同步项目环境状态
  if (props.project) {
    props.project.environments.forEach(env => {
      // 如果环境正在倒计时，则不更新其状态
      if (!countdownStates.value[env.id]?.isCountingDown) {
        env.isActive = activeEnvironments.value.includes(env.id);
      }
    });
  }
};

// 暴露方法给父组件调用
defineExpose({
  updateActiveEnvironments
});

// 环境类型颜色映射
const environmentTypeColors: Record<EnvironmentType, string> = {
  development: 'green',
  test: 'orange',
  preview: 'purple',
  production: 'red',
  custom: 'blue',
};

// 环境类型名称映射
const environmentTypeNames: Record<EnvironmentType, string> = {
  development: '开发环境',
  test: '测试环境',
  preview: '预发布环境',
  production: '正式环境',
  custom: '自定义环境',
};

// 获取环境类型颜色
const getEnvironmentTypeColor = (type: EnvironmentType): string => {
  return environmentTypeColors[type] || 'default';
};

// 获取环境类型名称
const getEnvironmentTypeName = (type: EnvironmentType): string => {
  return environmentTypeNames[type] || '未知环境';
};

// 代理规则生效提示倒计时
const startRuleEffectCountdown = (envId: string, targetState: boolean) => {
  // 清除之前的倒计时
  clearCountdown(envId);
  
  const countdownState = {
    isCountingDown: true,
    timeLeft: 6,
    targetState,
    progress: 0,
    timer: undefined as number | undefined
  };
  
  countdownStates.value[envId] = countdownState;
  
  const updateCountdown = () => {
    const state = countdownStates.value[envId];
    if (!state) return;
    
    state.timeLeft -= 0.1;
    state.progress = ((6 - state.timeLeft) / 6) * 100;
    
    if (state.timeLeft <= 0) {
      // 倒计时结束，显示代理规则生效成功提示
      showRuleEffectSuccess(envId, state.targetState);
      clearCountdown(envId);
    } else {
      state.timer = window.setTimeout(updateCountdown, 100);
    }
  };
  
  countdownState.timer = window.setTimeout(updateCountdown, 100);
};

const clearCountdown = (envId: string) => {
  const state = countdownStates.value[envId];
  if (state?.timer) {
    window.clearTimeout(state.timer);
    
    // 取消倒计时时，只是隐藏提示，不改变真实的激活状态
    // （因为激活状态已经是真实的了，只是取消代理规则生效提示）
  }
  delete countdownStates.value[envId];
};

// 显示代理规则生效成功提示
const showRuleEffectSuccess = (envId: string, targetState: boolean) => {
  const environment = props.project.environments.find(env => env.id === envId);
  const envName = environment?.name || '环境';
  const actionText = targetState ? '激活' : '取消激活';
  message.success(`${envName} 代理规则${actionText}生效成功！`);
};

// 环境开关切换处理 (立即真实激活版本)
const onEnvironmentToggle = async (id: string, checked: boolean, envType: EnvironmentType) => {
  // 检查是否已经在倒计时中
  const currentCountdown = countdownStates.value[id];
  
  if (currentCountdown?.isCountingDown) {
    // 如果已经在倒计时，则取消并重新计算
    clearCountdown(id);
  }
  
  // 1. 立即执行真实的激活/取消操作
  if (checked) {
    // 立即激活环境
    storageManager.addActiveEnvironmentsWithInfo(id, envType, props.project.id);
  } else {
    // 立即取消激活环境
    const allProjects = [{
      id: props.project.id,
      environments: props.project.environments.map(env => ({ id: env.id }))
    }];
    storageManager.deleteActiveEnvironments(id, allProjects);
  }

  // 2. 立即更新本地状态
  activeEnvironments.value = storageManager.getActiveEnvironments();
  
  // 3. 立即更新UI状态
  const environment = props.project.environments.find(env => env.id === id);
  if (environment) {
    environment.isActive = checked;
  }
  
  // 4. 启动代理规则生效提示倒计时
  startRuleEffectCountdown(id, checked);
  
  // 5. 通知父组件环境变化
  emit('environmentChange', id, checked, envType);
};

// 编辑项目
const onEdit = () => {
  // 只有管理员才能编辑
  if (!props.isAdmin) {
    message.warning('请先登录管理员账号');
    return;
  }
  emit('edit', props.project.id);
};

// 删除项目
const onDelete = async () => {
  try {
    await projectApi.delete(props.project.id);
    message.success('项目删除成功');
    emit('delete', props.project.id);
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};

// 初始化时获取活跃环境
updateActiveEnvironments();

// 监听项目数据变化，同步环境激活状态
watch(() => props.project, (newProject) => {
  if (newProject) {
    // 同步环境激活状态（但跳过正在倒计时的环境）
    const activeIds = activeEnvironments.value.length > 0 ? activeEnvironments.value : storageManager.getActiveEnvironments();
    newProject.environments.forEach(env => {
      // 如果环境正在倒计时，则不更新其状态
      if (!countdownStates.value[env.id]?.isCountingDown) {
        env.isActive = activeIds.includes(env.id);
      }
    });
  }
}, { deep: true, immediate: true });
</script>

<style scoped>
.project-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.project-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.project-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.environments-section h4 {
  margin: 16px 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.environments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

/* 自定义滚动条样式 */
.environments-list::-webkit-scrollbar {
  width: 6px;
}

.environments-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.environments-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.environments-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.environment-item {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background-color: #f0f9ff !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  transition: all 0.2s ease;
}

.environment-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.environment-name {
  font-weight: 600;
  color: #1890ff;
}

.environment-hosts {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.host-item {
  max-width: 100%;
}

/* 基础规则显示样式 */
.rule-item :deep(.ant-tag.host-tag) {
  font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', 'Consolas', monospace !important;
  font-size: 13px !important;
  font-weight: 400 !important;
  padding: 0 !important;
  border: none !important;
  background: transparent !important;
  color: #262626 !important;
  word-break: break-all !important;
  white-space: normal !important;
  height: auto !important;
  line-height: 1.4 !important;
  box-shadow: none !important;
  margin: 0 !important;
  transition: color 0.2s ease !important;
}

.rule-item :deep(.ant-tag.host-tag:hover) {
  background: transparent !important;
  color: #1890ff !important;
}

/* 可点击规则样式 */
.rule-item :deep(.ant-tag.clickable-rule) {
  cursor: pointer !important;
  transition: all 0.2s ease !important;
}

.rule-item :deep(.ant-tag.clickable-rule:hover) {
  background: #e6f7ff !important;
  color: #1890ff !important;
  transform: translateY(-1px) !important;
  text-decoration: underline !important;
}



.environment-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 12px;
  color: #1890ff;
  font-weight: 500;
}

/* 手风琴式规则显示样式 */
.environment-rules {
  margin-bottom: 12px;
}

.rules-accordion {
  background: transparent !important;
}

.rules-accordion :deep(.ant-collapse-item) {
  border: 1px solid #f0f0f0 !important;
  border-radius: 6px !important;
  margin-bottom: 0 !important;
  background: #fafafa !important;
}

.rules-accordion :deep(.ant-collapse-header) {
  padding: 8px 12px !important;
  background: #f5f5f5 !important;
  border-radius: 6px 6px 0 0 !important;
  border-bottom: 1px solid #e8e8e8 !important;
}

.rules-accordion :deep(.ant-collapse-content) {
  border-top: none !important;
  background: #fff !important;
}

.rules-accordion :deep(.ant-collapse-content-box) {
  padding: 12px !important;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.rules-count {
  font-size: 12px;
  color: #1890ff;
  font-weight: 600;
}

.env-type-tag {
  margin-left: 8px;
  font-size: 11px !important;
  padding: 2px 6px !important;
  height: auto !important;
  line-height: 1.2 !important;
}

.rules-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
  padding-right: 4px;
}

/* 自定义滚动条样式 */
.rules-content::-webkit-scrollbar {
  width: 4px;
}

.rules-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.rules-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
  transition: background 0.3s ease;
}

.rules-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.rule-item {
  display: flex;
  align-items: center;
  padding: 2px 0;
  margin-bottom: 4px;
}

/* 倒计时浮层样式 */
.countdown-overlay {
  position: absolute;
  top: -8px;
  right: -8px;
  background: rgba(255, 255, 255, 0.98);
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 220px;
  backdrop-filter: blur(4px);
  animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
  from {
    transform: translateX(20px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.countdown-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.countdown-text {
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
  text-align: center;
  line-height: 1.4;
}

.progress-container {
  width: 100%;
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
  border-radius: 2px;
  transition: width 0.1s linear;
  box-shadow: 0 0 4px rgba(24, 144, 255, 0.3);
}

.countdown-actions {
  display: flex;
  justify-content: center;
}

.countdown-actions .ant-btn {
  font-size: 12px;
  height: 24px;
  padding: 0 8px;
  color: #666;
  border: none;
  transition: all 0.2s ease;
}

.countdown-actions .ant-btn:hover {
  color: #1890ff;
  background-color: #f0f9ff;
}

/* 确保环境控制区域有相对定位 */
.environment-control {
  position: relative;
}
</style>
